#include "list.h"

list *new_list() {

    list *newlist = malloc(sizeof(list));
    newlist->first = malloc(sizeof(cell));
    newlist->last = newlist->first;
    newlist->first->next = NULL;
    newlist->first->prev = NULL;
    return newlist;
}


void add_element(list *p_list, char *element) {
    p_list->last->next = malloc(sizeof(cell));
    p_list->last->next->prev = p_list->last;
    p_list->last = p_list->last->next;
    p_list->last->next = p_list->first;
    p_list->last->val = element;
}


unsigned int has_element(list *p_list, char *element) {
  
  if (p_list == NULL || p_list->first == NULL) return FALSE;
  
  cell *searcher = p_list->first->next; // halting head cell
  
  while (searcher != p_list->first) {
    if (!strcmp(searcher->val, element)) return TRUE;
    searcher = searcher->next;
  }
  
  return FALSE;
}

void remove_element(list *plist, char *element) {

    pointer searcher = plist->first;
    pointer del_searcher;

    while (searcher->next != plist->first) {

        if (strcmp(searcher->next->val, element)) {
            // Distincts elements
            searcher = searcher->next;
        }
        else {
            del_searcher = searcher->next;
            searcher->next = del_searcher->next;
	    del_searcher->next->prev = searcher;
            del_searcher->next = del_searcher->prev = NULL;
            free(del_searcher);
            break;
        }
    }
}


void free_list(list *flist) {

    pointer fcell = flist->first;

    while (flist->first != flist->last) {
        flist->first = flist->first->next;
        free(fcell);
        fcell = flist->first;
    }

    free(flist->first);
    free(flist);
}


void print_list(const list *plist) {

    pointer print_cell = plist->first->next;

    while (print_cell != plist->first) {
        printf("List element: %s\n", print_cell->val);
        print_cell = print_cell->next;
    }
}



